package com.miya.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.miya.demo.common.constant.CommonConstant;
import com.miya.demo.common.util.Assert;
import com.miya.demo.entity.UserRole;
import com.miya.demo.model.dto.system.UserAddOrUpdateDTO;
import com.miya.demo.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miya.demo.mapper.UserMapper;
import com.miya.demo.entity.User;
import com.miya.demo.service.UserService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;
    /**
     * 新增/编辑用户
     *
     * @param userDTO 用户dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdate(UserAddOrUpdateDTO userDTO) {
        Assert.isFalse(StrUtil.isNotEmpty(userDTO.getEmail()) && !Validator.isEmail(userDTO.getEmail()), "email格式不正确。");
        Assert.isFalse(StrUtil.isNotEmpty(userDTO.getPhone()) && !Validator.isMobile(userDTO.getPhone()), "电话号码格式不正确。");
        User user = null;
        if (userDTO.getId() == null) {
            // 新增
            user = this.lambdaQuery()
                    .eq(User::getUsername, userDTO.getUsername())
                    .last(CommonConstant.SQL_LIMIT_ONE)
                    .one();
            Assert.isNull(user, "用户名已存在。");
            user = new User();
        } else {
            // 编辑
            user = this.getById(userDTO.getId());
            Assert.notNull(user, "用户不存在。");
            // 删除已存在的用户角色信息
            LambdaUpdateWrapper<UserRole> wrapper = Wrappers.lambdaUpdate(UserRole.class)
                    .eq(UserRole::getUserId, userDTO.getId());
            userRoleService.remove(wrapper);
        }
        BeanUtil.copyProperties(userDTO, user, CopyOptions.create().ignoreNullValue());
        user.setPassword(DigestUtil.bcrypt(userDTO.getPassword()));
        this.saveOrUpdate(user);

        List<Long> roles = userDTO.getRoles();
        if (CollUtil.isNotEmpty(roles)) {
            List<UserRole> userRoles = CollUtil.newArrayList();
            for (Long roleId : roles) {
                userRoles.add(new UserRole(user.getId(), roleId));
            }
            userRoleService.saveBatch(userRoles);
        }
    }

}


